//
//  BannerCollectionViewCell.swift
//  iPhone
//
//  Created by Toj on 5/24/23.
//

import UIKit
import GoogleMobileAds

class BannerCollectionViewCell: UICollectionViewCell {
    
    private weak var _delegate: UICollectionViewCellDelegate?
    
    var cellModel: BannerAdCellModel? { didSet {
        guard let model = cellModel else { return }
        print("-->toj: func:\(#function), adUnitID:\(model.adUnitID)")
        
        numberLabel.text = model.number
        
        guard !model.isNeedLayout else {
            model.isNeedLayout = false
            return
        }
        
        guard !model.adUnitID.isEmpty else { return }
        if _adView == nil {
            setupAdView(model: model)
        }
        _adView?.removeFromSuperview()
        loadAdView(model: model)
    } }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupMakeAddSubviews()
        setupMakeInitialize()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        print("-->toj: func: prepareForReuse BannerAdCell")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* numberLabel */
    private lazy var numberLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        return view
    }()
    
    /* adContentView */
    private lazy var adContentView = UIView()
    /* adView */
    private var _adView: GADBannerView?
    
    deinit {
        print("-->toj: class: \(cm_objectName), func: \(#function)")
    }
}

extension BannerCollectionViewCell {
    
    func loadAdView(model: BannerAdCellModel) {
        print("-->toj: func:\(#function), adUnitID:\(model.adUnitID)")
        _adView?.adUnitID = model.adUnitID
        _adView?.adSize = GADAdSizeFromCGSize(model.willShowCellSize)
        // let size = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(model.willShowCellSize.width)
        //_adView?.adSize = size
        _adView?.load(GADRequest())
    }
}

extension BannerCollectionViewCell: UICollectionViewCellDataSource {
    
    var delegate: UICollectionViewCellDelegate? {
        get {
            return _delegate
        }
        set {
            _delegate = newValue
        }
    }
    
    var dataModel: UICollectionViewCellModelProtocol? {
        get {
            return cellModel
        }
        set {
            cellModel = newValue as? BannerAdCellModel
        }
    }
}

extension BannerCollectionViewCell: GADBannerViewDelegate {
    
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("-->toj: func:\(#function), adUnitID:\(bannerView.adUnitID)")
        setupAddAdView()
        cellModel?.setupCellSize()
        cellModel?.isNeedLayout = true
        // setNeedsLayout()
        // delegate?.collectionViewInvalidateLayout()
//        guard bannerView.adUnitID == cellModel?.adUnitID else { return }
//
//
       delegate?.collectionViewReloadCell(self)
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        print("-->toj: func:\(#function), adUnitID:\(bannerView.adUnitID)")
        print("-->toj: func: \(#function) msg: \(error.localizedDescription)")
        cellModel?.resetCellSize()
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
        
        cellModel?.isNeedLayout = false
        print("-->toj: func: \(#function)")
    }
    
    func bannerViewDidRecordClick(_ bannerView: GADBannerView) {
        
        print("-->toj: func: \(#function)")
    }
    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("-->toj: func: \(#function)")
        
    }
    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
        
        print("-->toj: func: \(#function)")
    }
    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
        
        print("-->toj: func: \(#function)")
    }
}

extension BannerCollectionViewCell {
    
    func setupAdView(model: BannerAdCellModel) {
        print("-->toj: func:\(#function), adUnitID:\(model.adUnitID)")
        let size = GADAdSizeFromCGSize(model.willShowCellSize)
        //let size = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(model.willShowCellSize.width)
        let adView = GADBannerView(adSize: size)
        adView.adUnitID = model.adUnitID
        adView.rootViewController = UIViewController.vc_currentNavigationTopViewController
        adView.delegate = self
        _adView = adView
    }
    
    private func setupAddAdView() {
        guard let adView = _adView else { return }
        adView.backgroundColor = .random
        adContentView.addSubview(adView)
        adView.snp.makeConstraints { make in
            make.edges.equalTo(contentView)
        }
    }
    
    private func setupMakeAddSubviews() {
        contentView.addSubview(adContentView)
        contentView.addSubview(numberLabel)
    }
    
    private func setupMakeLayoutSubviews() {
        numberLabel.snp.makeConstraints { make in
            make.edges.equalTo(contentView)
        }
        
        adContentView.snp.makeConstraints { make in
            make.edges.equalTo(contentView)
        }
        
        guard let adView = _adView, adView.superview != nil else { return }
        adView.snp.remakeConstraints { make in
            make.edges.equalTo(contentView)
        }
    }
    
    private func setupMakeInitialize() {
        contentView.backgroundColor = .random
    }
}
